package com.example.egmvc1.controller;

import com.example.egmvc1.basic.response.JsonResult;
import com.example.egmvc1.mapper.UserMapper;
import com.example.egmvc1.pojo.dto.UserInsertParam;
import com.example.egmvc1.pojo.entity.User;
import com.example.egmvc1.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user")
@Api(tags = "01.用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    @ApiOperationSupport(order = 10)
    public JsonResult addUser(@Validated UserInsertParam userInsertParam) {
        log.debug("userInsertParam=" + userInsertParam);
        User user = new User();
        BeanUtils.copyProperties(userInsertParam, user);
        user.setCreateTime(new java.util.Date());
        user.setUpdateTime(new java.util.Date());
        int num = userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询用户列表")
    @ApiOperationSupport(order = 20)
    public JsonResult userList() {
//        List<UserListVO> userList = userMapper.selectUserList();
        return JsonResult.ok(userMapper.selectUserList());
    }

    @PostMapping("/del")
    @ApiOperation(value = "删除用户")
    @ApiOperationSupport(order = 30)
    @ApiImplicitParam(name = "id", value = "用户id", type = "Long")
    public JsonResult delUser(@NotEmpty @Range(min = 0, message = "id不能小于0") @RequestParam  Long id) {
        /*if(id<0){
            throw new IllegalArgumentException("id不能小于0");
        }*/
        int num = userMapper.delUser(id);
        return JsonResult.ok(num);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改用户")
    @ApiOperationSupport(order = 40)
    public JsonResult updateUser(User userParam) {
        log.debug("userParam=" + userParam);
        userParam.setUpdateTime(new java.util.Date());
        int num = userMapper.updateUser(userParam);
        return JsonResult.ok(num);
    }
}
